package com.wolfman.socket.server.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    private static final String URL = "jdbc:mysql:///socket";
    private static final String USER = "root";
    private static final String PASSWORD = "2001";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();
    private static final int connectionPoolMaxNumber = 145;
    private static final LinkedBlockingDeque<Connection> connectionPool = new LinkedBlockingDeque<>();
    private static int connectionSize = 0;

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        Connection connection = connectionThreadLocal.get();
        try {
            if (connection == null) {
                synchronized (JDBCUtils.class) {
                    if (connectionSize < connectionPoolMaxNumber) {
                        connection = DriverManager.getConnection(URL, USER, PASSWORD);
                        connectionSize++;
                    } else {
                        connection = connectionPool.poll(1, TimeUnit.SECONDS);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connectionThreadLocal.set(connection);
        }
        return connection;
    }

    /**
     * 释放资源
     */
    public static void close() {
        Connection connection = connectionThreadLocal.get();
        try {
            if (connection != null) {
//                connection.close();
                connectionPool.offer(connection, 1, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connectionThreadLocal.remove();
        }
    }

    /**
     * 释放资源
     */
    public static void close(Statement statement) {
        close(statement, null);
    }

    /**
     * 释放资源
     */
    public static void close(Statement statement, ResultSet resultSet) {
        try {
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
